import _get from 'lodash-es/get.js';
import _set from 'lodash-es/set.js';

function install(app) {
  try {
    Object.defineProperty(window, '__GLOBAL_VUE_APP', {
      value: app,
      enumerable: false,
      configurable: false,
      writable: false,
    });
  } catch (e) {
    console.log('vueGlobal.js: ', e);
  }
  const version = Number(app.version.split('.')[0]);
  if (version < 3) {
    _set(window.__GLOBAL_VUE_APP, 'STORE_PATH', 'prototype');
  } else {
    _set(window.__GLOBAL_VUE_APP, 'STORE_PATH', 'config.globalProperties');
  }
  console.log('vueGlobal installed ', _get(window.__GLOBAL_VUE_APP, 'STORE_PATH'), app);
}

function getApp() {
  return window.__GLOBAL_VUE_APP;
}

function getStore() {
  const app = getApp();
  return _get(app, _get(app, 'STORE_PATH'));
}

function get(name, type, handle) {
  if (arguments.length > 2) {
    [name, type, handle] = arguments;
  } else {
    [name, type] = arguments;
    if (typeof type === 'function') {
      handle = type;
    }
  }
  let val = _get(getStore(), name);
  if (typeof type === 'string' && type) {
    val = typeof val === type ? val : void 0;
  }
  if (typeof handle === 'function') {
    return val !== void 0 ? handle(val) : void 0;
  }
  return val;
}

function set(name, value) {
  _set(getStore(), name, value);
}

function cover(name, value) {
  _set(getStore(), name, value);
}

function use() {
  const app = getApp();
  app.use.apply(app, arguments);
}

function component() {
  const app = getApp();
  app.component.apply(app, arguments);
}

export default { install, component, use, get, set, cover, getApp };
